<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

class Order extends Base
{
    public function index()
    {
        if (request()->isAjax()) {

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            //订单状态
            if (isset($param['searchStatus']) && !empty($param['searchStatus'])) {
                if ($param['searchStatus'] == 5) {
                    //页面显示需要，把0设成所有的，把5设成待接单，所以要转换回来
                    $param['searchStatus'] = 0;
                }
                $where['status'] = ['EQ', $param['searchStatus']];
            }
            //订单编号
            if (isset($param['searchNumber']) && !empty($param['searchNumber'])) {
                $where['number'] = ['like', '%' . $param['searchNumber'] . '%'];
            }
            //公众号
            if (isset($param['searchAccount']) && !empty($param['searchAccount'])) {
                $where['account'] = ['like', '%' . $param['searchAccount'] . '%'];
            }
            //联系人
            if (isset($param['searchContact']) && !empty($param['searchContact'])) {
                $where['contact'] = ['like', '%' . $param['searchContact'] . '%'];
            }
            //渠道专员
            if (isset($param['searchUserName']) && !empty($param['searchUserName'])) {
                $where['user_name'] = ['like', '%' . $param['searchUserName'] . '%'];
            }

            if (isset($param['searchStartDate']) && !empty($param['searchStartDate'])
                && isset($param['searchEndDate']) && !empty($param['searchEndDate'])
            ) {
                //有开始日期有结束日期
                $where['datepicker'] = ['between time', [$param['searchStartDate'], $param['searchEndDate']]];
            } else if (isset($param['searchStartDate']) && !empty($param['searchStartDate'])
                && (!isset($param['searchEndDate']) || empty($param['searchEndDate']))
            ) {
                //有开始日期无结束日期
                $where['datepicker'] = ['>= time', $param['searchStartDate']];
            } else if ((!isset($param['searchStartDate']) || empty($param['searchStartDate']))
                && isset($param['searchEndDate']) && !empty($param['searchEndDate'])
            ) {
                //无开始日期有结束日期
                $where['datepicker'] = ['<= time', $param['searchEndDate']];
            }

            $selectResult = db('putorder')->where($where)->limit($offset, $limit)->order('id desc')->select();

            cache('user_data' . session('username'), $selectResult);

            foreach ($selectResult as $key => $vo) {

                if ($vo['status'] == 2 && strtotime($vo['datepicker'] . ' 00:00:00') < time()) {
                    $vo['status'] = 3;
                    $id[] = $vo['id'];
                }

                switch ($vo['status']) {
                    case 0:
                        $operate = [
                            '接单' => "javascript:orderTake('" . $vo['id'] . "')",
                            '编辑' => url('order/orderEdit', ['id' => $vo['id']]),
                            '撤销' => "javascript:orderDel('" . $vo['id'] . "')"
                        ];
                        $selectResult[$key]['operate'] = showOperate($operate);
                        break;
                    case 1:
                        $operate = [
                            '下单' => "javascript:orderTake('" . $vo['id'] . "')",
                            '编辑' => url('order/orderEdit', ['id' => $vo['id']]),
                            '撤销' => "javascript:orderDel('" . $vo['id'] . "')"
                        ];
                        $selectResult[$key]['operate'] = showOperate($operate);
                        break;
                    case 2:
                        $operate = [
                            '编辑' => url('order/orderEdit', ['id' => $vo['id']]),
                            '撤销' => "javascript:orderDel('" . $vo['id'] . "')"
                        ];
                        $selectResult[$key]['operate'] = showOperate($operate);
                        break;
                    default:
                        $selectResult[$key]['operate'] = '';
                        break;
                }

                switch ($vo['status']) {
                    case 0:
                        $selectResult[$key]['status'] = '待接单';
                        break;
                    case 1:
                        $selectResult[$key]['status'] = '进行中';
                        break;
                    case 2:
                        $selectResult[$key]['status'] = '已下单';
                        break;
                    case 3:
                        $selectResult[$key]['status'] = '已完成';
                        break;
                    case 4:
                        $selectResult[$key]['status'] = '已撤销';
                        break;
                    default:
                        $selectResult[$key]['status'] = '未定义';
                        break;
                }

                switch ($vo['source']) {
                    case 1:
                        $selectResult[$key]['source'] = '纽狮下单';
                        break;
                    case 2:
                        $selectResult[$key]['source'] = '报系下单';
                        break;
                    default:
                        $selectResult[$key]['source'] = '未定义';
                        break;
                }

                switch ($vo['content']) {
                    case 1:
                        $selectResult[$key]['content'] = '微信贴片';
                        break;
                    case 2:
                        $selectResult[$key]['content'] = '微信软文';
                        break;
                    default:
                        $selectResult[$key]['content'] = '未定义';
                        break;
                }

                //节约空间，把它们拼成两行
                $selectResult[$key]['number'] = $vo['number'] . '<br>' . $selectResult[$key]['status'];
                $selectResult[$key]['contact'] = $vo['contact'] . '<br>' . $vo['phone'];
                $selectResult[$key]['user_name'] = $vo['user_name'] . '<br>' . $vo['user_phone'];
                $selectResult[$key]['serv_name'] = $vo['serv_name'] . '<br>' . $vo['serv_phone'];
            }

            if (!empty($id)) {
                //更新数据库，把到时间的订单，状态改成已完成
                db('putorder')->where('id', 'in', $id)->setField('status', 3);
            }

            $return['total'] = db('putorder')->where($where)->count();  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return $this->fetch();
    }

    /**
     * 订单编辑
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     */
    public function orderEdit()
    {
        if (request()->isPost()) {
            $ok = db('putorder')->where('id', input('edit_id'))->update(array('price' => input('price'), 'datepicker' => input('datepicker'), 'source' => input('source'), 'content' => input('content'), 'position' => input('position'), 'serv_name' => input('serv_name'), 'serv_phone' => input('serv_phone')));
            return json(['code' => $ok, 'data' => '', 'msg' => $ok == 1 ? '成功' : '失败']);
        }

        $id = input('param.id');
        $order = db('putorder')->where('id', $id)->find();

        $order['contact'] = $order['contact'] . ' / ' . $order['phone'];
        $order['user_name'] = session('username') . ' / ' . session('phone');

        $this->assign([
            'order' => $order
        ]);

        return $this->fetch('orderedit_wx');
    }

    //操作订单
    public function orderTake()
    {
        $id = input('param.id');

        try {
            $data = db('putorder')->where('id', $id)->field('status')->find();
            if ($data['status'] == 0) {
                db('putorder')->where('id', $id)->update(['user_name' => session('username'), 'user_phone' => session('phone')]);
            }
            db('putorder')->where('id', $id)->setInc('status');
            $flag = ['code' => 1, 'data' => '', 'msg' => '成功'];
        } catch (PDOException $e) {
            $flag = ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }

    //撤销订单
    public function orderDel()
    {
        $id = input('param.id');

        try {
            db('putorder')->where('id', $id)->update(array('status' => 4));
            $flag = ['code' => 1, 'data' => '', 'msg' => '成功'];
        } catch (PDOException $e) {
            $flag = ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }

    public function outExcel()
    {
        import("excel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("纽狮新媒体")
            ->setLastModifiedBy("纽狮新媒体")
            ->setTitle("订单表格")
            ->setSubject("订单管理")
            ->setDescription("")
            ->setKeywords("")
            ->setCategory("");

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('订单');

        // 加粗
        for ($i = 'A'; $i <= 'O'; $i++) {
            $objPHPExcel->getActiveSheet()->getStyle($i . '1')->getFont()->setBold(true);
        }

        //设置列宽
        for ($i = 'A'; $i <= 'O'; $i++) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($i)->setWidth('15');
        }

        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', '订单编号')
            ->setCellValue('B1', '订单状态')
            ->setCellValue('C1', '订单来源')
            ->setCellValue('D1', '订单内容')
            ->setCellValue('E1', '账号')
            ->setCellValue('F1', '位置')
            ->setCellValue('G1', '时间')
            ->setCellValue('H1', '联系人')
            ->setCellValue('I1', '联系电话')
            ->setCellValue('J1', '渠道专员')
            ->setCellValue('K1', '渠道电话')
            ->setCellValue('L1', '服务支持')
            ->setCellValue('M1', '服务电话')
            ->setCellValue('N1', '订单价')
            ->setCellValue('O1', '结算价');

// Add some data
        $data = cache('user_data' . session('username'));

        foreach ($data as $key => $vo) {
            switch ($vo['status']) {
                case 0:
                    $vo['status'] = '待接单';
                    break;
                case 1:
                    $vo['status'] = '进行中';
                    break;
                case 2:
                    $vo['status'] = '已下单';
                    break;
                case 3:
                    $vo['status'] = '已完成';
                    break;
                case 4:
                    $vo['status'] = '已撤销';
                    break;
                default:
                    $vo['status'] = '未定义';
                    break;
            }
            switch ($vo['source']) {
                case 1:
                    $vo['source'] = '纽狮下单';
                    break;
                case 2:
                    $vo['source'] = '报系下单';
                    break;
                default:
                    $vo['source'] = '未定义';
                    break;
            }

            switch ($vo['content']) {
                case 1:
                    $vo['content'] = '微信贴片';
                    break;
                case 2:
                    $vo['content'] = '微信软文';
                    break;
                default:
                    $vo['content'] = '未定义';
                    break;
            }

            $objPHPExcel->getActiveSheet()
                ->setCellValueExplicitByColumnAndRow(0, 2 + $key, $vo['number'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueByColumnAndRow(1, 2 + $key, $vo['status'])
                ->setCellValueByColumnAndRow(2, 2 + $key, $vo['source'])
                ->setCellValueByColumnAndRow(3, 2 + $key, $vo['content'])
                ->setCellValueByColumnAndRow(4, 2 + $key, $vo['account'])
                ->setCellValueByColumnAndRow(5, 2 + $key, $vo['position'])
                ->setCellValueByColumnAndRow(6, 2 + $key, $vo['datepicker'])
                ->setCellValueByColumnAndRow(7, 2 + $key, $vo['contact'])
                ->setCellValueByColumnAndRow(8, 2 + $key, $vo['phone'])
                ->setCellValueByColumnAndRow(9, 2 + $key, $vo['user_name'])
                ->setCellValueByColumnAndRow(10, 2 + $key, $vo['user_phone'])
                ->setCellValueByColumnAndRow(11, 2 + $key, $vo['serv_name'])
                ->setCellValueByColumnAndRow(12, 2 + $key, $vo['serv_phone'])
                ->setCellValueByColumnAndRow(13, 2 + $key, $vo['price'])
                ->setCellValueByColumnAndRow(14, 2 + $key, $vo['deal_price']);
        }

// Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="订单表.xlsx"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}
